<?php
namespace app\common\model\orderreceipt;

use app\api\controller\Pub;
use app\common\model\buss\Buss;
use app\common\model\coll\Collection;
use app\common\model\cost\Costtype;
use app\common\model\orderdata\Goods;
use app\common\model\orderhawa\HawaList;
use app\common\model\power\Rolepower;
use app\common\model\transit\Transitcompany as TransitCompany;
use app\common\model\transit\Transport;
use app\common\model\user\User;
use think\Model;

class ReceiptList extends Model
{
    // 设置当前模型对应的完整数据表名称
    protected $table = 'receiptlist';
    protected $pk    = 'ReceiptListId';

    const STATEINT       = 0; //创建状态
    const STATEWAIT      = 0; //等待核实
    const STATEOK        = 1; //已完成
    const STATEDELETE    = 3; //被删除的订单
    const STATEARRAY     = [['待下单', '已下单'], ['待确认', '已完成']];
    const ORDERNUMBERPER = 'B';

    public function bussinfo()
    {
        return $this->hasOne('app\common\model\buss\Buss', 'UserId', 'BussinessId');
    }
    public function wareinfo()
    {
        return $this->hasOne('app\common\model\user\User', 'UserId', 'WarehouseId');
    }
    public function tranuserinfo()
    {
        return $this->hasOne('app\common\model\user\User', 'UserId', 'TransitUserId');
    }
    public function bussuserinfo()
    {
        return $this->hasOne('app\common\model\user\User', 'UserId', 'BussinessId');
    }

    public function listinfo()
    {
        return $this->hasMany('app\common\model\orderreceipt\Receipt', 'ReceiptListId', 'ReceiptListId');
    }

    /**
     * 状态分类
     * @param  string $value [description]
     * @return [type]        [description]
     */
    public static function getStatusText($value = '')
    {
        $status = [-1 => '全部订单', 0 => '待确认', 1 => '已完成'];
        if ($value !== '') {
            return $status[$value];
        }
        return $status;
    }

    /**
     * 获取订单列表
     * @return [type] [description]
     */
    public static function usergetlist($data, $type = 'ware')
    {
        $rdata    = ReceiptList::where('State', '<>', ReceiptList::STATEDELETE);
        $userinfo = User::getinfo();
        if ($type == 'ware') {
            $rdata   = $rdata->where('WarehouseId', $userinfo->UserId);
            $rdata   = $rdata->with(['bussinfo', 'listinfo','tranuserinfo','bussuserinfo']);
            $visible = ['ReceiptListId', 'State', 'WarehouseTime', 'BussinessTime', 'OrderNumber', 'bussinfo.UserName', 'bussinfo.CardNumber', 'bussinfo.CarNumber', 'bussinfo.UserTel', 'bussinfo.UserImg', 'bussinfo.CarImg','tranuserinfo.Name','tranuserinfo.RoleName','bussuserinfo.Name','bussuserinfo.RoleName'];
        } else if ($type == 'buss') {
            $rdata   = $rdata->where('BussinessId', $userinfo->UserId);
            $rdata   = $rdata->with(['listinfo','tranuserinfo','bussuserinfo']);
            $visible = ['ReceiptListId', 'State', 'WarehouseTime', 'BussinessTime', 'OrderNumber','tranuserinfo.Name','tranuserinfo.RoleName','bussuserinfo.Name','bussuserinfo.RoleName'];
        } else if ($type == 'tran') {
            $rdata   = $rdata->where('TransitUserId', $userinfo->UserId);
            $rdata   = $rdata->with(['listinfo']);
            $visible = ['ReceiptListId', 'State', 'WarehouseTime', 'BussinessTime', 'OrderNumber'];
        } else if ($type == 'acco') {
            $rdata   = $rdata->with(['bussinfo', 'listinfo','tranuserinfo','bussuserinfo']);
            $visible = ['ReceiptListId', 'State', 'WarehouseTime', 'BussinessTime', 'OrderNumber', 'bussinfo.UserName', 'bussinfo.CardNumber', 'bussinfo.CarNumber', 'bussinfo.UserTel', 'bussinfo.UserImg', 'bussinfo.CarImg', 'SettlementTime', 'TotalCost','tranuserinfo.Name','tranuserinfo.RoleName','bussuserinfo.Name','bussuserinfo.RoleName'];
        }
        $option = come_model_option($data, $rdata);
        $rdata  = $option['rdata'];
        $data   = $option['data'];
        $rdata  = $rdata->select();
        $rdata->visible($visible);

        $ndata['list'] = $rdata->toArray();

        $goodid = get_array_id($ndata, 'GoodId', 'list', 'listinfo');
        if (empty($goodid)) {
            $ndata['goodinfo'] = Goods::getlist($goodid);
        } else {
            $ndata['goodinfo'] = [];
        }
        $ndata['statetext'] = ReceiptList::getStatusText();
        $ndata['pageinfo']  = ['pageindex' => $data['pageindex'], 'pagemax' => $data['count']];
        return $ndata;
    }

    /**
     * 获取订单列表
     * @return [type] [description]
     */
    public static function Managetlist($data, $state = -1)
    {
        if ($state == -1) {
            $rdata = ReceiptList::where('State', '<>', ReceiptList::STATEDELETE);
        } else {
            $rdata = ReceiptList::where('State', $state);
        }
        $option = come_model_option($data, $rdata);
        $rdata  = $option['rdata'];
        $data   = $option['data'];
        $rdata  = $rdata->with(['bussinfo', 'listinfo','bussuserinfo','tranuserinfo']);

        $rdata = $rdata->select();
        $visible = ['ReceiptListId', 'State', 'WarehouseTime', 'BussinessTime', 'OrderNumber', 'bussinfo.UserName', 'bussinfo.CardNumber', 'bussinfo.CarNumber', 'bussinfo.UserTel', 'bussinfo.UserImg', 'bussinfo.CarImg', 'SettlementTime', 'TotalCost','tranuserinfo.Name','tranuserinfo.RoleName','bussuserinfo.Name','bussuserinfo.RoleName'];
        $rdata->visible($visible);

        $ndata['list']      = $rdata->toArray();
        $goodid             = get_array_id($ndata, 'GoodId', 'list', 'listinfo');
        $ndata['goodinfo']  = Goods::getlist($goodid);
        $ndata['statetext'] = ReceiptList::getStatusText();
        $ndata['pageinfo']  = ['pageindex' => $data['pageindex'], 'pagemax' => $data['count']];
        return $ndata;
    }

    /**
     * 判断列表中的产品状态是否可操作
     * @param  [type] $list [id数组]
     * @return [type]       [返回错误代码]
     */
    public static function liststate($id, $hidden = [], $hidloag = true)
    {
        $data = ReceiptList::where('State', '<>', ReceiptList::STATEDELETE)->where('ReceiptListId', $id)->find();
        if (empty($data)) {
            return moerr('没有找到您需要的订单');
        } else {
            if ($hidloag) {
                $hidden = array_merge(['OperationLog'], $hidden);
                $data   = $data->hidden($hidden)->toArray();
            } elseif (empty($hidden)) {
                $data = $data->toArray();
            } else {
                $data = $data->hidden($hidden)->toArray();
            }
            return sok($data);
        }
    }
    /**
     * 获取订单信息
     * @param  [type] $id [description]
     * @return [type]     [description]
     */
    public static function getinfo($id, $type = 'ware')
    {
        if ($type == 'buss' || $type == 'hawa') {
            $data = self::liststate($id, ['SettlementImg', 'SettlementNote', 'SettlementTime', 'FloatingNote']);
        } elseif ($type == 'mana') {
            $data = self::liststate($id, [], false);
        } else {
            $data = self::liststate($id);
        }

        if (!$data['code']) {return $data;}
        $rdata              = $data['msg'];
        $rdata['GoodsList'] = Receipt::getlist($rdata, $type);
        if ($type == 'buss') {
            if ($rdata['BussinessId'] !== Pub::userid()) {
                return moerr('没有权限');
            }
            if ($rdata['State'] == ReceiptList::STATEOK) {
                $opdata['Type']    = 'buss';
                $opdata['where'][] = ['ReceiptListId', $rdata['ReceiptListId']];
                $rdata['hawalist'] = HawaList::usergetlist($opdata, 'buss', false);
            } else {
                $rdata['hawalist'] = [];
            }
        } elseif ($type == 'tran') {
            if ($rdata['TransitUserId'] !== Pub::userid()) {
                return moerr('没有权限');
            }
            if ($rdata['State'] == ReceiptList::STATEOK) {
                $opdata['Type']    = 'buss';
                $opdata['where'][] = ['ReceiptListId', $rdata['ReceiptListId']];
                $rdata['hawalist'] = HawaList::usergetlist($opdata, 'tran', false);
            } else {
                $rdata['hawalist'] = [];
            }
        } else if ($type == 'ware') {
            $rdata['buss'] = (empty($rdata['BussinessId']) ? [] : Buss::user_getinfo($rdata['BussinessId']));
        } else if ($type == 'acco') {
            if ($rdata['State'] == ReceiptList::STATEOK) {
                $opdata['where'][] = ['ReceiptListId', $rdata['ReceiptListId']];
                $rdata['hawalist'] = HawaList::usergetlist($opdata, 'acco', false);
            } else {
                $rdata['hawalist'] = [];
            }
            $rdata['coll'] = Collection::user_getinfo($rdata['BussinessId']);
            $rdata['buss'] = (empty($rdata['BussinessId']) ? [] : Buss::user_getinfo($rdata['BussinessId']));
            $rdata['cost'] = Costtype::getcostlist($id, 'orderreceipt');
        } else if ($type == 'mana') {
            if ($rdata['State'] == ReceiptList::STATEOK) {
                $opdata['where'][] = ['ReceiptListId', $rdata['ReceiptListId']];
                $rdata['hawalist'] = HawaList::usergetlist($opdata, 'mana', false);
            } else {
                $rdata['hawalist'] = [];
            }
            $rdata['buss'] = (empty($rdata['BussinessId']) ? [] : Buss::user_getinfo($rdata['BussinessId']));
            if (Rolepower::ispower(203008)) {
                $rdata['cost'] = Costtype::getcostlist($id, 'orderreceipt');
            }
        }
        $rdata['tran'] = (empty($rdata['TransitCompanyId']) ? [] : TransitCompany::user_getinfo($rdata['TransitCompanyId']));
        if (!empty($rdata['TransitUserId'])) {
            $rdata['tran']['user'] = User::getpublicinfo($rdata['TransitUserId']);
        }
        $rdata['tran']['sport'] = Transport::get($rdata['TranSportId']);
        $rdata['ware']          = User::getpublicinfo($rdata['WarehouseId']);
        $rdata['StateList']     = ReceiptList::STATEARRAY;
        return ['code' => true, 'msg' => $rdata];

    }

    /**
     * 新增方法
     * @param  [type] $data [description]
     * @return [type]       [description]
     */
    public static function screate($idata)
    {
        $userinfo = User::getinfo();
        //判断是否连续触发
        // $sb = Buss::user_getinfo($idata['bussid']);
        // if(empty($sb)){
        //     return moerr('没有找到您需要的收集员');
        // }
        //基础信息
        $data['State']       = ReceiptList::STATEINT;
        $data['OrderNumber'] = ReceiptList::ORDERNUMBERPER . date('YmdH') . $idata['bussid'] . rand(10, 99);
        //产废人信息
        $data['BussinessId'] = $idata['bussid'];
        //入库信息
        $data['WarehouseId']   = $userinfo->UserId;
        $data['WarehouseNote'] = $idata['WarehouseNote'];
        $data['WarehouseTime'] = date('Y-m-d H:i', time());
        //报价信息
        $data['QuotationListId'] = $idata['quot']['QuotationListId'];
        $data['QuotationCost']   = $idata['quot']['QuotationCost'];
        $data['FloatingCost']    = $idata['quot']['FloatingCost'];
        $data['TotalCost']       = $idata['quot']['TotalCost'];
        //运输信息
        $data['TransitCompanyId'] = $idata['tcid'];
        $data['TranSportId']      = $idata['tsid'];
        $data['TransitUserId']    = $idata['tuid'];
        // dump($data);
        // return myerr('数据错误');
        //保存主表
        $ReceiptList   = ReceiptList::create($data);
        $ReceiptListId = $ReceiptList->ReceiptListId;
        //保存子表
        $receipt = Receipt::screate($ReceiptListId, $idata['goodlist'], $idata['valuelist'], $idata['quot']['pricelist'],$idata['orderGoodName'],$idata['orderid']);
        //判断子表是否保存成功
        if (!$receipt['code']) {
            $ReceiptList->delete();
            return serr($receipt['msg']);
        }
        return sok($ReceiptList);
    }

    /**
     * 判断订单数组状态是否完全一致
     * @param  [type] $data  [description]
     * @param  [type] $state [description]
     * @return [type]        [description]
     */
    public static function test_state($data, $state)
    {
        $sb = ReceiptList::where('ReceiptListId', 'in', $data)->where('State', $state)->count();
        if ($sb == count($data)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 订单分配
     * @param  [type] $data [description]
     * @return [type]       [description]
     */
    public static function dist($data)
    {
        $userinfo = User::getinfo();
        if (!empty($data['ids'])) {
            $sb = ReceiptList::where('ReceiptListId', 'in', $data['ids']);
        } else if (!empty($data['id'])) {
            $sb = ReceiptList::where('ReceiptListId', $data['id']);
        } else {
            return moerr('分配参数错误');
        }

        $count = $sb->update(['DistributionTime' => date('Y-m-d H:i', time()),
            'DistributionUserId'                     => $userinfo->UserId,
            'BussinessId'                            => $data['bussid'],
            'State'                                  => 1]);
        if (empty($count)) {
            return moerr('没有找到需要分配的订单');
        }
        return sok('成功分配' . $count . '个订单。');
    }

    /**
     * 修改收集员
     * @param  [type] $data [description]
     * @return [type]       [description]
     */
    public static function changedist($data)
    {
        $userinfo = User::getinfo();
        if (!empty($data['id']) && !empty($data['bussid'])) {
            $sb = ReceiptList::where('ReceiptListId', $data['id'])->find();
        } else {
            return moerr('分配参数错误');
        }
        if ($sb->State >= 3) {
            return moerr('订单已在运输中无法修改收集员');
        }
        $sb->save(['DistributionTime' => date('Y-m-d H:i', time()),
            'DistributionUserId'          => $userinfo->UserId,
            'BussinessId'                 => $data['bussid'],
            'State'                       => 1]);
        return sok('修改成功');
    }

    /**
     * 用户修改信息
     * @param  [type]  $data   [description]
     * @param  boolean $wtnote [是否记录]
     * @return [type]          [description]
     */
    public static function user_reinfo($data, $wtnote = true, $showerr = true)
    {
        if (empty($data['id'])) {
            return moerr('缺少重要参数');
        }
        $info     = ReceiptList::get($data['id']);
        $userinfo = User::getinfo();
        $reinfo   = empty($info->OperationLog) ? '' : $info->OperationLog . "\n";
        $reinfo   = $reinfo . '【' . $userinfo->Name . '|' . $userinfo->UserId . '】在' . date('Y-m-d H:i', time()) . '进行了信息调整：';
        $nreinfo  = '';
        foreach ($data as $key => $value) {
            $sb = $info->getfiledname($key);
            if (empty($sb)) {
                continue;
            }
            //取原数据
            $ovalue = $info->$key;
            if ($key == 'State' && $value !== $ovalue) {
                $info->$key = $value;
                //value将改变成文字所以提前赋值
                $value   = $info->getStatusText((int) $value);
                $ovalue  = $info->getStatusText((int) $ovalue);
                $nreinfo = $nreinfo . '字段【' . $info->getfiledname($key) . '】由【' . $ovalue . '】修改为【' . $value . '】;' . "\n";
            } else if (!empty($value) && $ovalue !== $value) {
                $nreinfo    = $nreinfo . '字段【' . $info->getfiledname($key) . '】由【' . $ovalue . '】修改为【' . $value . '】;' . "\n";
                $info->$key = $value;
            }
        }
        if (!empty($nreinfo)) {
            if ($wtnote) {
                $reinfo             = $reinfo . "\n" . $nreinfo;
                $info->OperationLog = $reinfo;
            }
            $info->save();
        } else {
            if ($showerr) {
                return moerr('没有找到需要调整的数据');
            }
        }
    }

    public static function getfiledname($str)
    {
        $filename = ['UpNote' => '下单备注', 'UpImg'          => '下单附带图片',
            'QuotationCost'       => '报价费用', 'FloatingCost'   => '浮差金额', 'TotalCost' => '合计金额',
            'FloatingNote'        => '浮差备注', 'SettlementImg'  => '结算凭证',
            'SettlementTime'      => '结算时间', 'SettlementNote' => '结算备注', 'State'     => '订单状态'];
        if (empty($filename[$str])) {
            return false;
        }
        return $filename[$str];
    }

    public static function getgoodinfo($bussid, $state)
    {
        $idarr = ReceiptList::where('State', $state)->where('BussinessId', $bussid);
        $idarr = $idarr->column('ReceiptListId');
        $data  = Hawa::where('ReceiptListId', 'in', $idarr)->group('GoodId')->with('good_info')->field('GoodId,sum(Weight) as Weight')->select();
        return $data;
    }

    /**
     * 货物入库
     * @param  [type] $data [description]
     * @return [type]       [description]
     */
    public static function receipt($data)
    {
        
        //修改订单
        $receipt                = ReceiptList::get($data['id']);
        $receipt->State         = ReceiptList::STATEOK;
        $receipt->BussinessTime = date('Y-m-d H:i', time());
        $receipt->save();
        return sok();
    }
    /**
     * 获取统计数据
     * @return [type] [description]
     */
    public static function getsummary($date = '', $enddate = '')
    {
        if (empty($date)) {
            $date = date('Y-m-d', time());
        } else {
            $date = date('Y-m-d', strtotime($date));
        }
        if (empty($enddate)) {
            $sb               = ReceiptList::where('BussinessTime', '>', $date)->where('BussinessTime', '<=', $date . ' 24:00')->field('TotalCost,ReceiptListId')->select();
            $rdata['timestr'] = mb_substr($date, 8, 2) . '号';
        } else {
            $enddate = date('Y-m-d', strtotime($enddate));
            $sb      = ReceiptList::where('BussinessTime', '>', $date)->where('BussinessTime', '<=', $enddate . ' 24:00')->field('TotalCost,ReceiptListId')->select();
            if (mb_substr($date, 5, 2) !== mb_substr($enddate, 5, 2)) {
                $rdata['timestr'] = mb_substr($date, 5, 5) . '~' . mb_substr($enddate, 6, 5);
            } else {
                $rdata['timestr'] = mb_substr($date, 8, 2) . '~' . mb_substr($enddate, 8, 2);
            }
        }
        if (empty($sb)) {
            return [];
        }
        if (empty($enddate)) {
            $rdata['wait'] = ReceiptList::where('BussinessTime', '>', $date)->where('BussinessTime', '<=', $date . ' 24:00')->whereNull('SettlementTime')->count();
        } else {
            $rdata['wait'] = ReceiptList::where('BussinessTime', '>', $date)->where('BussinessTime', '<=', $enddate . ' 24:00')->whereNull('SettlementTime')->count();
        }

        $Receiptlists      = get_array_id($sb, 'ReceiptListId');
        $rdata['goodlist'] = Receipt::where('ReceiptListId', 'in', $Receiptlists)->group('GoodId')->with('goodInfo')->field('GoodId,sum(Weight) as Weight')->select();
        $rdata['Weight']   = 0;
        foreach ($rdata['goodlist'] as $key => $value) {
            $rdata['Weight'] = $value['Weight'] + $rdata['Weight'];
        }

        if ($rdata['Weight'] > 1000) {
            $rdata['Weight']     = $rdata['Weight'] / 1000;
            $rdata['WeightUnit'] = '吨';
        } else {
            $rdata['WeightUnit'] = '公斤';
        }
        $rdata['Price'] = 0;
        foreach ($sb as $key => $value) {
            $rdata['Price'] = $value['TotalCost'] + $rdata['Price'];
        }
        if ($rdata['Price'] > 1000) {
            $rdata['Price']     = $rdata['Price'] / 10000;
            $rdata['PriceUnit'] = '万元';
        } else {
            $rdata['PriceUnit'] = '元';
        }
        return $rdata;
    }
    /**
     * 获取统计数据
     * @return [type] [description]
     */
    public static function getsummaryinfo($date = '', $enddate = '')
    {
        if (empty($date)) {
            $date = date('Y-m-d', time());
        } else {
            $date = date('Y-m-d', strtotime($date));
        }
        if (empty($enddate)) {
            echo "string";
            $sb               = ReceiptList::where('WarehouseTime', '>', $date)->where('WarehouseTime', '<=', $date . ' 24:00')->field('WarehouseTime,BussinessId,TotalCost,ReceiptListId')->select();
            $rdata['timestr'] = mb_substr($date, 8, 2) . '号';
        } else {
            $enddate = date('Y-m-d', strtotime($enddate));
            $sb      = ReceiptList::where('WarehouseTime', '>', $date)->where('WarehouseTime', '<=', $enddate . ' 24:00')->field('WarehouseTime,BussinessId,TotalCost,ReceiptListId')->select();
            if (mb_substr($date, 5, 2) !== mb_substr($enddate, 5, 2)) {
                $rdata['timestr'] = mb_substr($date, 5, 5) . '~' . mb_substr($enddate, 6, 5);
            } else {
                $rdata['timestr'] = mb_substr($date, 8, 2) . '~' . mb_substr($enddate, 8, 2);
            }
        }
        if (count($sb) == 0) {
            return [];
        }
        $Receiptlists      = get_array_id($sb, 'ReceiptListId');
        $rdata['goodlist'] = Receipt::where('ReceiptListId', 'in', $Receiptlists)->field('ReceiptListId,GoodId,Weight')->select();

        $ReceiptListIdinfo = [];
        foreach ($rdata['goodlist'] as $key => $value) {
            if (empty($ReceiptListIdinfo[$value['ReceiptListId']])) {
                $ReceiptListIdinfo[$value['ReceiptListId']] = $value['Weight'];
            } else {
                $ReceiptListIdinfo[$value['ReceiptListId']] += $value['Weight'];
            }
        }
        $rdata['Weight'] = 0;
        //获取日期的
        foreach ($sb as $key => $value) {
            $dataindex = substr($value['WarehouseTime'], 5, 5);
            if (empty($rdata['datalist'][$dataindex]['weight'])) {
                $rdata['datalist'][$dataindex]['weight'] = $ReceiptListIdinfo[$value['ReceiptListId']];
            } else {
                $rdata['datalist'][$dataindex]['weight'] += $ReceiptListIdinfo[$value['ReceiptListId']];
            }
            if (empty($rdata['datalist'][$dataindex]['cost'])) {
                $rdata['datalist'][$dataindex]['cost'] = $value['TotalCost'];
            } else {
                $rdata['datalist'][$dataindex]['cost'] += $value['TotalCost'];
            }

        }

        //获取业务员的
        $useridlist = [];
        foreach ($sb as $key => $value) {
            $dataindex = $value['BussinessId'];
            if (empty($rdata['userlist'][$dataindex])) {
                $rdata['userlist'][$dataindex]['weight'] = $ReceiptListIdinfo[$value['ReceiptListId']];
                $useridlist[]                            = $dataindex;
            } else {
                $rdata['userlist'][$dataindex]['weight'] += $ReceiptListIdinfo[$value['ReceiptListId']];
            }

            if (empty($rdata['userlist'][$dataindex]['cost'])) {
                $rdata['userlist'][$dataindex]['cost'] = $value['TotalCost'];
            } else {
                $rdata['userlist'][$dataindex]['cost'] += $value['TotalCost'];
            }
        }
        //获取每个业务员每天的
        $userdatalist = [];
        foreach ($sb as $key => $value) {
            $dataindex  = substr($value['WarehouseTime'], 5, 5);
            $dataindex2 = $value['BussinessId'];

            if (empty($rdata['userlist'][$dataindex2]['list'][$dataindex]['weight'])) {
                $rdata['userlist'][$dataindex2]['list'][$dataindex]['weight'] = $ReceiptListIdinfo[$value['ReceiptListId']];
            } else {
                $rdata['userlist'][$dataindex2]['list'][$dataindex]['weight'] += $ReceiptListIdinfo[$value['ReceiptListId']];
            }

            if (empty($rdata['userlist'][$dataindex2]['list'][$dataindex]['cost'])) {
                $rdata['userlist'][$dataindex2]['list'][$dataindex]['cost'] = $value['TotalCost'];
            } else {
                $rdata['userlist'][$dataindex2]['list'][$dataindex]['cost'] += $value['TotalCost'];
            }
        }
        $rdata['namelist'] = Buss::getlistname($useridlist);
        return $rdata;
    }

}
